/*
 * @Description: 我的申请context
 * @Author: Rfan
 * @Date: 2023-02-10 11:12:18
 * @LastEditTime: 2023-02-28 11:08:34
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { MyApplyReducer } from '../reducers/MyApplyReducer';
import {
  EDIT_APPROVE_ITEM,
  HIDE_APPROVE_DIALOG,
  SET_APPLY_LIST,
  SET_ARC_LIST,
  SET_LIST_QUERY
} from '../constants';
import { fetchBorrowProcessDetail } from '@/api/workFlow/workflow';
import { taskStateList } from '../dictionaries';
import { fetchApplyListByPage, fetchTaskDetail, startTask } from '@/api/workFlow/task';
import { message } from 'antd';
import { appState } from '@/store/mobx';
import { selectItemByKey } from '@/utils/list';
import update from 'immutability-helper';

const initialState = {
  listQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {
      taskState: 0
    }
  },
  // 借阅单列表
  approveList: [],
  // 借阅单内文件列表
  activeArcList: [],

  // 查看申请弹窗显示状态
  checkDialogVisible: false,

  approveDialog: {
    visible: false,
    data: null
  },

  // 审核状态
  taskStateList
};

const MyApplyContext = createContext();

const MyApplyContextProvider = (props) => {
  const [state, dispatch] = useReducer(MyApplyReducer, initialState);

  const actions = {
    setListQuery(query) {
      dispatch({ type: SET_LIST_QUERY, data: query });
    },

    /**
     * @description: 获取审核任务列表
     * @param {IPageQuery<IApplyListParams>} query
     */
    getApproveList(query) {
      query.param.userId = appState.userInfo.id;

      return new Promise((resolve, reject) => {
        fetchApplyListByPage(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_APPLY_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    showFlowNodeDialog(id) {
      return new Promise((resolve) => {
        fetchTaskDetail(id).then((res) => {
          const { data } = res;
          resolve(data);
        });
      });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    hideApproveDialog(data) {
      dispatch({ type: HIDE_APPROVE_DIALOG, data });
    },

    setArcList(id) {
      fetchBorrowProcessDetail(id).then((res) => {
        const { data } = res;
        console.log('arc list', data);
        dispatch({ type: SET_ARC_LIST, list: data.archiveItemList || [] });
      });
    },

    startTaskFunc(params) {
      startTask(params).then(() => {
        message.success('申请成功');
        const selectItem = selectItemByKey(params.businessKey, state.approveList, 'applyFormNo');
        const data = update(selectItem, {
          status: {
            $set: selectItem.status + 1
          }
        });
        dispatch({ type: EDIT_APPROVE_ITEM, data, id: data.id });
      });
    }
  };

  const filters = {
    stateFilter(id) {
      return state.taskStateList.find((item) => item.id === id)?.name || '-';
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {}, []);

  return (
    <MyApplyContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </MyApplyContext.Provider>
  );
};

export const useMyApplyContext = () => {
  return useContext(MyApplyContext);
};

export { MyApplyContext, MyApplyContextProvider };
